//
//  AppDelegate.m
//  League
//
//  Created by 博宇 李 on 2018/1/18.
//  Copyright © 2018年 ciyuanjuzhen. All rights reserved.
//

#import "AppDelegate.h"
#import "LBTabBarController.h"
#import <RongIMLib/RongIMLib.h>
#import <RongIMKit/RongIMKit.h>
#import <UserNotifications/UserNotifications.h>
#import "RYMessageViewController.h"
#import "UserInfomation.h"
#import "LoginModel.h"
#import "OCLoginViewController.h"

//RCIMUserInfoDataSource   用户信息提供者
@interface AppDelegate ()<UITabBarDelegate,RCIMUserInfoDataSource,RCIMGroupInfoDataSource,RCIMGroupMemberDataSource,UNUserNotificationCenterDelegate>
@property(strong , nonatomic)UINavigationController *nav;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 1.创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // 2.设施window的背景颜色
    self.window.backgroundColor = [UIColor whiteColor];
//    // 3.设置根视图控制器
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        
        NSLog(@"第一次启动");

          [InternationalControl setUserlanguage:@"zh-Hans"];
        
    }else{
        NSLog(@"不是第一次启动");
    }
    
    [UIApplication sharedApplication].applicationIconBadgeNumber =  [[RCIMClient sharedRCIMClient] getTotalUnreadCount];
//    [UIApplication sharedApplication].applicationIconBadgeNumber =  [[RCIMClient sharedRCIMClient] getTotalUnreadCount];

    NSLog(@"%@",@(application.applicationIconBadgeNumber));
    
//    self.window.rootViewController =self.nav;
    // 4.显示窗口
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    [defaults setObject:@”jack“ forKey:@"isFirst"];
    
    
/** Jin 自动登录逻辑改到LoginViewController
 
    if ([[[NSUserDefaults standardUserDefaults] stringForKey:kIsLogin] isEqualToString:kLoginStr]) {
        NSLog(@"登录了的");
    
//        [self SetUPIsLoginViewController];
//        [self SetRY];
        [self loginRequest];
//
//        [[RCIM sharedRCIM] initWithAppKey:@"82hegw5u8dtux"];
//        [[RCIM sharedRCIM] connectWithToken:@"z6xJRAexBVx1qKsmZUAw2QspaPp6e2lp+pw0LWIZBJTrKh4bhzaRu2NFn0wacZ0X+CKBzrKkYSlVVLnDrQGrLg=="     success:^(NSString *userId) {
//            NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
//            [[RCIM sharedRCIM] setUserInfoDataSource:self];
//            [[RCIM sharedRCIM] setGroupInfoDataSource:self];
//            [[RCIM sharedRCIM] setEnableMessageMentioned:YES];
//            [RCIM sharedRCIM].globalNavigationBarTintColor=kAppColor;
//            //        [RCIM sharedRCIM].groupMemberDataSource = self;
//            [RCIM sharedRCIM].currentUserInfo = [[RCUserInfo alloc] initWithUserId:@"testcc" name:@"当前登录用户的用户名" portrait:@"http://www.mf08s.com/y/q/UploadFiles_q/20121005/2012100507413841.jpg"];
//            // 设置消息体内是否携带用户信息
//            [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
//            [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
//        } error:^(RCConnectErrorCode status) {
//            NSLog(@"登陆的错误码为:%ld", (long)status);
//        } tokenIncorrect:^{
//            //token过期或者不正确。
//            //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
//            //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
//            NSLog(@"token错误");
//        }];
    }
    else{

        NSLog(@"没有登录");
        [[RCIMClient sharedRCIMClient] disconnect:NO];
        [self SetUPNoLoginViewController];

    }
    **/
    [self SetUPNoLoginViewController];
    /** end */
    
    
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self selector:@selector(receiveNotification:) name:kChangeLoginNotificationName object:nil];
    
    NSNotificationCenter *loginOut = [NSNotificationCenter defaultCenter];
    [loginOut addObserver:self selector:@selector(outLog:) name:kOutLoginNotificationName object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguage) name:kChangeLanguage object:nil];
    
    
    
   
    
    if ([application
         respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        //注册推送, 用于iOS8以及iOS8之后的系统
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:(UIUserNotificationTypeBadge |
                                                                  UIUserNotificationTypeSound |
                                                                  UIUserNotificationTypeAlert)
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    } else {
        
        //注册推送，用于iOS8之前的系统
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeAlert |
        UIRemoteNotificationTypeSound;
        [application registerForRemoteNotificationTypes:myTypes];
        
        
    }
//     [self requestAuthor];
    NSDictionary *remoteNotificationUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"remoteNotificationUserInfo:%@",remoteNotificationUserInfo);
    
//    NSDictionary *NotificationUserInfo = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
//    NSLog(@"NotificationUserInfo:%@",NotificationUserInfo);
    UILocalNotification *localNotification =
    launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
    
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromLaunchOptions:launchOptions];
    if (pushServiceData) {
        NSLog(@"该启动事件包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"%@", pushServiceData[key]);
        }
    } else {
        NSLog(@"该启动事件不包含来自融云的推送服务");
    }
    
    //init im
    [[RCIMClient sharedRCIMClient] initWithAppKey:@"82hegw5u8dtux"];
    
    //设置SVProgressHUD显示时间
    [SVProgressHUD setMaximumDismissTimeInterval:3.0];
    
    
    return YES;
}
-(void)SetRY
{
    UserInfomation *user = [UserInfomation shareManager];
    [[RCIMClient sharedRCIMClient] connectWithToken:user.rongYunToken success:^(NSString *userId) {
        NSLog(@"sharedRCIMClient-userId:%@", userId);
    } error:^(RCConnectErrorCode status) {
        NSLog(@"sharedRCIMClient-status:%@", @(status));
    } tokenIncorrect:^{
        NSLog(@"sharedRCIMClient-token error");
    }];
    
    return;
    
    
    [[RCIM sharedRCIM] initWithAppKey:@"82hegw5u8dtux"];
    [[RCIM sharedRCIM] connectWithToken:user.rongYunToken     success:^(NSString *userId) {
        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
        [[RCIM sharedRCIM] setUserInfoDataSource:self];
        [[RCIM sharedRCIM] setGroupInfoDataSource:self];
        [[RCIM sharedRCIM] setEnableMessageMentioned:YES];
        [RCIM sharedRCIM].globalNavigationBarTintColor=kAppColor;
        //        [RCIM sharedRCIM].groupMemberDataSource = self;
        [RCIM sharedRCIM].currentUserInfo = [[RCUserInfo alloc] initWithUserId:user.pk name:user.username portrait:user.picUrl];
        [RCIM sharedRCIM].enableMessageAttachUserInfo = YES;
        [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%d", status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"token错误");
    }];
}
//- (void)requestAuthor
//{
//    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
//        // 设置通知的类型可以为弹窗提示,声音提示,应用图标数字提示
//        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
//        // 授权通知
//        [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
//    }
//}

- (void)loginRequest {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if(![defaults objectForKey:kUserName] || ![defaults objectForKey:kUserPassWord]){
        return;
    }
    NSDictionary *dic = @{
                          @"phone":[defaults objectForKey:kUserName],
                          @"password":[defaults objectForKey:kUserPassWord]
                          };
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",kFirstUrl,kLoginUrl];
    [DataContrller PostRequestUrl:urlStr Param:dic requestSuccess:^(NSDictionary *backDic) {
        NSLog(@"backDic:%@",backDic);
        if ([backDic[@"returnCode"] integerValue] == 200) {
            LoginModel *model = [[LoginModel alloc] initWithDictionary:backDic[@"obj"] error:nil];
            UserInfomation *user = [UserInfomation shareManager];
            user.username = model.username;
            user.phone = model.phone;
            user.pk = model.pk;
            user.rongYunToken = model.rongYunToken;
            user.picUrl = model.picUrl;
            [self SetUPIsLoginViewController];
            [self SetRY];
        } else {
            //登录失败
            [[RCIMClient sharedRCIMClient] disconnect:NO];
            [self SetUPNoLoginViewController];
        }
    } requestFail:^(NSString *backErrorStr) {
        //登录失败
        [[RCIMClient sharedRCIMClient] disconnect:NO];
        [self SetUPNoLoginViewController];
    }];
}

    //注册用户通知设置
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
    // register to receive notifications
    [application registerForRemoteNotifications];
    
    
    NSLog(@"?????????????????????");
    NSLog(@"notificationSettings:%@",notificationSettings);
    
    
    
    
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
   
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"1内容userInfo:%@",notification);
    NSLog(@"?????????????????????");

    
//    NSDictionary *remoteNotificationUserInfo = notification[UIApplicationLaunchOptionsRemoteNotificationKey];
//    NSLog(@"remoteNotificationUserInfo:%@",remoteNotificationUserInfo);
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // userInfo为远程推送的内容

    NSLog(@"2内容userInfo:%@",userInfo);
    NSLog(@"?????????????????????");
    
    NSNotification *notification =[NSNotification notificationWithName:kPushName_FirstVc object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:notification];

    
    NSDictionary *remoteNotificationUserInfo = userInfo[UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"remoteNotificationUserInfo:%@",remoteNotificationUserInfo);
    
    // http://www.rongcloud.cn/docs/ios_push.html
    // cType   会话类型。PR 指单聊、 DS 指讨论组、 GRP 指群组、 CS 指客服、SYS 指系统会话、 MC 指应用内公众服务、 MP 指跨应用公众服务。
    // alert远程推送显示的内容。自带的消息会有默认显示，如果您使用的是自定义消息，需要在发送时设置。对应于 iOS 发送消息接口中的 pushContent。
    // fId 消息发送者的用户 ID。
    // oName 消息类型，参考融云消息类型表.消息标志；可自定义消息类型。
    //tId Target ID。
    // appData     远程推送的附加信息，对应于 iOS 发送消息接口中的 pushData。
    
    
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromLaunchOptions:userInfo];
    if (pushServiceData) {
        NSLog(@"该启动该启动事件包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"%@", pushServiceData[key]);
        }
    } else {
        NSLog(@"该启动事件不包含来自融云的推送服务");
    }
    
    
    
}

- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {

    
    NSLog(@"个人----%@",userId);
    if ([userId isEqualToString:@"ctest3"]) {
        RCUserInfo *userInfo = [[RCUserInfo alloc] init];
        userInfo.userId = userId;
        userInfo.name = @"333333";
        userInfo.portraitUri = @"http://www.mf08s.com/y/q/UploadFiles_q/20121005/2012100507413841.jpg";
        return completion(userInfo);
    }
    else
    {
        RCUserInfo *userInfo = [[RCUserInfo alloc] init];
        userInfo.userId = userId;
        userInfo.name = @"222222";
        userInfo.portraitUri = @"https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=479216235,3399005187&fm=27&gp=0.jpg";
        return completion(userInfo);
    }
    return completion(nil);
    
// return completion(user);
}
//群组信息提供者
- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion
{
    NSLog(@"群组----%@",groupId);
}

-(void)changeLanguage
{
    [self SetUPNoLoginViewController];
}

- (void)receiveNotification:(NSNotification *)noti{
    
    [self SetRY];
    
    
    [self SetUPIsLoginViewController];
    
    
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)outLog:(NSNotification *)noti{
//    [[RCIM sharedRCIM] initWithAppKey:@"82hegw5u8dtux"];
//    [[RCIM sharedRCIM] connectWithToken:@""     success:^(NSString *userId) {
//        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
//        [[RCIM sharedRCIM] setUserInfoDataSource:self];
//        [[RCIM sharedRCIM] setGroupInfoDataSource:self];
//        [[RCIM sharedRCIM] setEnableMessageMentioned:YES];
//        [RCIM sharedRCIM].globalNavigationBarTintColor=kAppColor;
//        //        [RCIM sharedRCIM].groupMemberDataSource = self;
//    } error:^(RCConnectErrorCode status) {
//        NSLog(@"登陆的错误码为:%d", status);
//    } tokenIncorrect:^{
//        //token过期或者不正确。
//        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
//        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
//        NSLog(@"token错误");
//    }];
//
    [[RCIMClient sharedRCIMClient]disconnect:NO];
    [self SetUPNoLoginViewController];
//     [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//没有登录的RootViewController
-(void)SetUPNoLoginViewController
{
//    LoginViewController *loginVc = [[LoginViewController alloc] init];
//    [self SetUPNavigationBar:loginVc];
//    self.window.rootViewController = self.nav;
//    [self.window makeKeyAndVisible];
//    return;
    
    //Jack 界面
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LoginRegister" bundle:nil];
    OCLoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"OCLoginViewController"];
    [self SetUPNavigationBar:loginVC];
    self.window.rootViewController = self.nav;
    [self.window makeKeyAndVisible];
}
//登录后的RootViewController
-(void)SetUPIsLoginViewController
{
//    FirstViewController *firstVC =[[FirstViewController alloc] init];
//    SecondViewController *secondVC =[[SecondViewController alloc] init];
//    ThirdViewController *thirdVC =[[ThirdViewController alloc] init];
//    self.tabBarController = [[ESTabBarController alloc] initWithTabIconNames:@[@"firstImage",@"firstImage",@"firstImage" ]];
//    [self.tabBarController setViewController:firstVC
//                                     atIndex:0];
//    [self.tabBarController setViewController:secondVC
//                                     atIndex:1];
//    [self.tabBarController setViewController:thirdVC
//                                     atIndex:2];
//    self.tabBarController.selectedColor = [UIColor whiteColor];
//    self.tabBarController.buttonsBackgroundColor = [UIColor blackColor];
//    //    [self.tabBarController highlightButtonAtIndex:0];
//    [self SetUPNavigationBar:self.tabBarController];
//    self.window.rootViewController =self.nav;
//    // 4.显示窗口
//    [self.window makeKeyAndVisible];

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    LBTabBarController *tabBarVc = [[LBTabBarController alloc] init];
    
    self.window.rootViewController = tabBarVc;
    [self.window makeKeyAndVisible];
    
   

//    CATransition *anim = [[CATransition alloc] init];
//    anim.type = @"rippleEffect";
//    anim.duration = 1.0;
    
    
//    [self.window.layer addAnimation:anim forKey:nil];
    
    
    
}
    

   
//设置状态栏
-(void)SetUPNavigationBar:(UIViewController *)rootViewController
{
    self.nav = [[UINavigationController alloc]initWithRootViewController:rootViewController];
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];//[UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:1.0]
    [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    //[[UINavigationBar appearance] setBarStyle:UIBarStyleDefault];//
    //[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    NSShadow *shadow = [[NSShadow alloc] init];
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName,shadow, NSShadowAttributeName,[UIFont fontWithName:kFontName size:20.0], NSFontAttributeName, nil]];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
    NSLog(@"");
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
